package ddz.net;

import ch.qos.logback.classic.Logger;
import com.kaka.notice.Command;
import com.kaka.notice.Message;
import com.kaka.util.StringUtils;
import org.slf4j.LoggerFactory;

/**
 * @author zkpursuit
 */
abstract public class LogicDataHandler extends Command implements WsSender {

    private static Logger logger = (Logger) LoggerFactory.getLogger(LogicDataHandler.class);

    @Override
    public void execute(Message msg) {
        if (msg instanceof ProtocolMessage) {
            ProtocolMessage pm = (ProtocolMessage) msg;
            try {
                this.execute(pm);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    }

    abstract protected void execute(ProtocolMessage msg) throws Exception;

    /**
     * 获取命令号
     *
     * @return 命令号
     */
    protected int opcode() {
        if (cmd() == null) {
            throw new RuntimeException("命令号不能为空！");
        }
        if (cmd() instanceof Integer || cmd() instanceof Short) {
            return (int) cmd();
        }
        if (cmd() instanceof String) {
            String cmdStr = (String) cmd();
            if (StringUtils.isInteger(cmdStr)) {
                return Integer.parseInt(cmdStr);
            }
        }
        throw new RuntimeException("命令号非整型数据！");
    }

}
